<?php

	require_once(realpath(dirname(__FILE__)) . "/../lib/TheliaPurifier.php");

	function lireVarFond($var, $varFond){
        if(preg_match("/#PARAM_FOND_$var=([0-9]*)/", $varFond, $rec))
        	return $rec[1];
        else return 0;
	}

	function lireVarUrl($var, $varUrl){
        if(preg_match("/&$var=([a-zA-Z0-9_\-]*)/", $varUrl, $rec))
        	return $rec[1];
        else return "";
	}

	// lecture des arguments
	function lireTag($ligne, $tag, $filtre = "", $purifier = 1){

		if( ! strstr($ligne, $tag)) return "";
        preg_match("/$tag=\"([^\"]*)\"/", "$ligne", $restag);

        if(preg_match("/^([^\+]*)\+(.*)$/", $filtre, $resfiltre)){
			$filtre = $resfiltre[1];
			$complement = $resfiltre[2];
		}
			else $complement = "";

		return filtrevar($restag[1], $filtre, $complement, $purifier);
	}

	function lireParam($param, $filtre="", $methode="", $purifier = 1){

		if($methode == "post")
			$tab = &$_POST;
		else if($methode == "get")
			$tab = &$_GET;
		else
			$tab = &$_REQUEST;

		if (isset($tab[$param]))
		{
			$param = $tab[$param];

			if(get_magic_quotes_gpc())
				$param = stripslashes($param);

	        if(preg_match("/^([^\+]*)\+(.*)$/", $filtre, $resfiltre)){
				$filtre = $resfiltre[1];
				$complement = $resfiltre[2];
			}
				else $complement = "";

			return filtrevar($param, $filtre, $complement, $purifier);
		}
		else
		{
			return '';
		}
	}

	function filtrevar($var, $filtre, $complement="", $purifier = 1){
		$erreur = 0;

		if($filtre == "" || $var == "")
			return $var;

		switch($filtre){
			case "int" : if(! preg_match("/^[0-9$complement]*$/", $var)) $erreur = 1; break;
			case "string_iso_strict" : if(! preg_match("/^[0-9a-zA-Z_]*$/", $var)) $erreur = 1; break;
			case "string": if($purifier) $var = TheliaPurifier::instance()->purifier($var); break;
			case "float" : if(! preg_match("/^[0-9\.\,$complement]*$/", $var)) $erreur = 1; break;
			case "int_list": if(! preg_match("/^[0-9\,$complement]*$/", $var)) $erreur = 1; break;
			case "string_list":	if($purifier) $var = TheliaPurifier::instance()->purifier($var); break;
			default: break;
		}

		if($erreur == 1)
			return "";

		// Pour les boucles
		$var = str_replace("\"", "&quot;", $var);
		return $var;

	}
?>